# -*- coding: UTF-8 -*-
 
import smtplib
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

mail_host='smtp.163.com'
mail_user='kayzhan@163.com'
mail_pass='79967394'
class BaseMail:
    def __init__(self, smtp, auth, sender, pwd):
        self.auth = auth
        self.smtp = smtp
        self.sender = sender
        self.pwd = pwd
 
    def _parserSend(self, subject, content, accessory):
        return subject, content, accessory  
      
    def send (self, subject, content, sendTo, lsCc=[], accessory=[]):
        mit = MIMEMultipart()
        mit['from'] = self.sender
        mit['to'] = ','.join(sendTo)
        if lsCc: mit['cc'] = ','.join(lsCc)
 
        codeSubject, codeContent, codePlugin = self._parserSend(subject, content, accessory)
        mit.attach(MIMEText(codeContent, 'html', 'utf-8'))
        mit['subject'] = codeSubject
        for plugin in codePlugin:
            mitFile = MIMEApplication(plugin['content'],)
            mitFile.add_header('content-disposition', 'attachment', filename=plugin['subject'])
            mit.attach(mitFile)
              
        server = smtplib.SMTP(self.smtp)
        # server.set_debuglevel(smtplib.SMTP.debuglevel)
        if self.auth: server.docmd("EHLO server")
        server.starttls()
        server.login(self.sender, self.pwd)
        server.sendmail(self.sender, sendTo , mit.as_string())
        server.close()
 
class Com63Mail(BaseMail):
    def __init__(self, sender=mail_user, pwd=mail_pass):
        BaseMail.__init__(self, mail_host, False, sender, pwd)
        self.__strcode = 'utf-8'
          
    def _parserSend(self, subject, content, accessory):
        for i in accessory:
            i['subject'] = i['subject'].encode('gbk')
        return subject, content.encode(self.__strcode), accessory
      
 
if __name__ == "__main__" :
    subject = u'python3000邮件发送测试'
    content = u'<font color="#FF0066">热门评论</color>'
    accessory = [{'subject' : u'附1abc.txt', 'content' : u'内容1abc'}]
    com163 = Com63Mail()
    sendTo = ['qinjiandong2010@gmail.com']
    lsCc = []
    com163.send(subject, content, sendTo, lsCc, accessory)
    print 'com163 send' 
